package thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * cyclicBarrier.await() 计数操作+等待操作双包 主子都用线程
 *
 * countDownLatch.countDown()子线程
 * countDownLatch.await()主线程
 *
 * @author yuank
 * @date 2024/12/27 19:22:13
 */
class ThreeUtil {
    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        cyclicBarrier cyclicBarrier = new cyclicBarrier();
        cyclicBarrier.run(); //jvm不一定按照顺序来
        System.out.println("主线程也调用cyclicBarrier");

        cyclicBarrier.getCyclicBarrier().await();

        System.out.println("----");
        System.out.println("四位一起达到终点");
        System.out.println("====");



        countDownLatch countDownLatch = new countDownLatch();

        System.out.println("主线程等待中");
        countDownLatch.run();
        countDownLatch.countDownLatch.await();
        System.out.println("到齐了");
    }
}

//new CyclicBarrier -循环屏障;线程数量进行计数
class cyclicBarrier {
    CyclicBarrier cyclicBarrier = new CyclicBarrier(4);
    public CyclicBarrier getCyclicBarrier() { return cyclicBarrier;}

    public void run() {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "正在输出");
                System.out.println(Thread.currentThread().getName() + "到达屏障");
                try { this.cyclicBarrier.await();
                } catch (InterruptedException e) { throw new RuntimeException(e);
                } catch (BrokenBarrierException e) { throw new RuntimeException(e);}
            }).start();
        }
    }
}

//new CountDownLatch -参照物-1进行计数
class countDownLatch {
    CountDownLatch countDownLatch = new CountDownLatch(3);
    public CountDownLatch getCountDownLatch() { return countDownLatch;}

    public void run() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + ",启动");
                long c = countDownLatch.getCount() -1;
                System.out.println("扣1,还剩计数:" + c);
                countDownLatch.countDown();
            }).start();
        }
    }
}

//new Semaphore -参照物-1&+1进行计数
class semaphore{}
